//1.滑动窗口 --- 最大连续1的个数
class Solution {
public:
    int longestOnes(vector<int>& nums, int k) {
        //这道题本质就是求一段区间最多有k个0, 求区间的最长长度
        int n = nums.size();
        int l = 0, r = 0, sum = 0, ret = 0;
        while(r < n)
        {
            if(nums[r] == 0) sum++;
            while(sum > k)
            {
                if(nums[l] == 0) sum--;
                l++;
            }
            ret = max(ret, r - l + 1);
            r++;
        }
        return ret;
    }
};

//2.滑动窗口 --- 将x减到0的最小操作数
class Solution {
public:
    int minOperations(vector<int>& nums, int x) {
        int sum = 0;
        for(auto a : nums) sum += a;
        if(sum < x) return -1;
        int t = sum - x; //0
        //这道题本质是求和为t的最长连续区间
        int l = 0, n = nums.size(), r = 0, ret = -1;
        sum = 0;
        while(r < n)
        {
            sum += nums[r];
            while(sum > t)
                sum -= nums[l++];
            if(sum == t)
                ret = max(ret, r - l + 1);
            r++;
        }
        return ret == -1 ? -1 : n - ret;
    }
};
